package com.idcard.readcard;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.widget.NestedScrollView;

import com.idcard.bean.IdCardData;
import com.idcard.enums.DecodeImageType;
import com.idcard.enums.ReadCardType;
import com.idcard.enums.StatusCode;
import com.idcard.listener.ReadCardListener;
import com.idcard.readcard.utils.DoubleClickUtil;
import com.idcard.readcard.utils.WaterMarkBg;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;


public class SamActivity extends Activity implements ReadCardListener {

    private boolean isInitOk = false;
    private boolean isStartRead = false;
    private TextView tv_state;
    private ImageView imgMan;
    private TextView txtName, txtSex, txtNation, tvCopyright, txtPolice, txtCardID, txtDeviceDN, tvVersion, txtAddress, txtValid, txtY, txtM, txtD;
    private Button bu_open, bu_close, bu_init;
    private NestedScrollView logNestedScrollView;
    private int readTime;

    // 读卡SDK
    private ReadSettingBuilder readSettingBuilder;
    private ReadCardOutMethod readCardManager;

    private final Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            String deviceId = readCardManager.readCardDeviceid();
            txtDeviceDN.setText(deviceId);
            tvVersion.setText(readCardManager.readFirmwareVersion());
        }
    };

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sam);
        initView();
        initBuilder();
        initlistener();
    }

    private void initView() {
        tv_state = findViewById(R.id.text);
        imgMan = findViewById(R.id.imgMan);
        txtName = findViewById(R.id.txtName);
        txtSex = findViewById(R.id.txtSex);
        txtNation = findViewById(R.id.txtNation);
        txtPolice = findViewById(R.id.txtPolice);
        txtCardID = findViewById(R.id.txtCardID);
        txtAddress = findViewById(R.id.txtAddress);
        txtValid = findViewById(R.id.txtValid);
        txtY = findViewById(R.id.txtY);
        txtM = findViewById(R.id.txtM);
        txtD = findViewById(R.id.txtD);
        bu_open = findViewById(R.id.bu_open);
        bu_close = findViewById(R.id.bu_close);
        txtDeviceDN = findViewById(R.id.txtDeviceDN);
        tvVersion = findViewById(R.id.tvVersion);
        bu_init = findViewById(R.id.bu_init);
        tvCopyright = findViewById(R.id.tvCopyright);
        logNestedScrollView = findViewById(R.id.log_scroll);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        try {
            String name = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
            tvCopyright.setText("版本号：" + name);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        TextView markText = findViewById(R.id.tv_mark);
        List<String> labels = new ArrayList<>();
        labels.add("身份证识别");
        markText.setBackgroundDrawable(new WaterMarkBg(this, labels, -30, 15));
    }

    /**
     * 统一配置读卡SDK参数信息
     * 测试使用的 appid 不可以用于商用(否则后果自负)。
     * 商用的 appid 请务必联系我司商务进行分配。
     */
    private void initBuilder() {

        readSettingBuilder = ReadCardManager.Companion
                .builder(getBaseContext())
                .buildOpenSound(true)
                .buildOpenLog(true, "")
                // 测试使用的 appid 不可以用于商用(否则后果自负)。
                // 商用的 appid 请务必联系我司商务进行分配。
                .buildAppId("test")
                .buildIpAndPort("", 0)
                .buildSerialPort("/dev/ttyS0", 115200)
                .buildReadCardType(ReadCardType.SAM_USB)
                .buildDecodeImageType(DecodeImageType.LOCAL_DECODE);

        readCardManager = readSettingBuilder.buildCreate();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void initlistener() {
        tv_state.setMovementMethod(ScrollingMovementMethod.getInstance());

        DoubleClickUtil.signleClick(bu_init, v -> initSDK());

        DoubleClickUtil.signleClick(bu_open, v -> openRead());

        DoubleClickUtil.signleClick(bu_close, v -> {
            closeRead();
            Toast.makeText(getBaseContext(), "关闭成功，请重新初始化", Toast.LENGTH_SHORT).show();
        });

        tv_state.setOnLongClickListener(v -> {
            tv_state.setText("清空日志");
            return true;
        });
    }

    private void initSDK() {
        if (isInitOk) {
            tv_state.append("\n已经初始化过了");
            Toast.makeText(SamActivity.this, "已经初始化过了", Toast.LENGTH_SHORT).show();
            return;
        }
        readCardManager.readCardInit(code -> {
            if (code == StatusCode.ININ_OK.getCode()) {
                isInitOk = true;
                Log.e("mtj", "初始化成功");
                runOnUiThread(() -> {
                    tv_state.setText("初始化成功");
                    bu_open.setEnabled(true);
                });
            } else {
                isInitOk = false;
                Log.e("mtj", "初始化失败 " + readCardManager.readCardType().getCodeTypeName());
                runOnUiThread(() -> {
                    tv_state.setText("初始化失败 " + readCardManager.readCardType().getCodeTypeName());
                    if (readCardManager.readCardType() != ReadCardType.SAM_SERIALPORT) {
                        readSettingBuilder.buildReadCardType(ReadCardType.SAM_SERIALPORT);
                        // 重试一次串口初始化
                        initSDK();
                    }
                });
            }
        });
    }

    private void openRead() {
        if (!isInitOk) {
            tv_state.append("\n请先初始化SDK");
            Toast.makeText(getBaseContext(), "请先初始化SDK", Toast.LENGTH_SHORT).show();
            return;
        }
        if (isStartRead) {
            tv_state.append("\n读卡已开启");
            Toast.makeText(getBaseContext(), "读卡已开启", Toast.LENGTH_SHORT).show();
            return;
        }
        isStartRead = true;
        bu_open.setEnabled(false);
        bu_close.setEnabled(true);
        readCardManager.readCardStart(SamActivity.this);
    }

    private void closeRead() {
        bu_close.setEnabled(false);
        bu_open.setEnabled(false);
        bu_init.setEnabled(true);
        isInitOk = false;
        isStartRead = false;
        readCardManager.readCardStop();
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onReadCardState(int type, @NotNull String msg) {
        //读卡失败
        if (type == 1022) {
            readTime++;
        }
        if (readTime % 100 == 0) {
            tv_state.setText("");
        }
        tv_state.append("\n");
        tv_state.append("status: " + type + "  ，msg:" + msg);
        handler.postDelayed(() -> {
            logNestedScrollView.fullScroll(View.FOCUS_DOWN);
        }, 200);
    }

    @Override
    public void onReadICCardSuccess(@NotNull String icnumber, int type) {
        clear();
        tv_state.append("\n");
        tv_state.append("type: " + type + "\nicnumber:" + icnumber);
        handler.postDelayed(() -> {
            logNestedScrollView.fullScroll(View.FOCUS_DOWN);
        }, 200);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onReadIDCardSuccess(@NotNull IdCardData bean) {
        clear();
        if (readTime % 100 == 0) {
            tv_state.setText("");
        }
        tv_state.append("\n");
        tv_state.append("解码完成");
        tv_state.append("\n");
        tv_state.append("解码耗时：" + bean.getDistime() + "ms");
        readTime++;
        if (null != bean.getBitmap()) {
            imgMan.setImageBitmap(bean.getBitmap());
        }
        txtName.setText(bean.getName());
        txtSex.setText(bean.getSex());
        txtNation.setText(bean.getNation());
        txtPolice.setText(bean.getIssue());
        txtCardID.setText(bean.getId());
        txtValid.setText(bean.getStartDate() + "-" + bean.getEndDate());
        try {
            txtY.setText(bean.getBirthday().substring(0, 4));
            txtM.setText(bean.getBirthday().substring(4, 6));
            txtD.setText(bean.getBirthday().substring(6, 8));
        } catch (Exception e) {
        }
        txtAddress.setText(bean.getAddress());
        handler.postDelayed(() -> {
            logNestedScrollView.fullScroll(View.FOCUS_DOWN);
        }, 200);
    }

    private void clear() {
        txtName.setText("");
        txtSex.setText("");
        txtNation.setText("");
        txtPolice.setText("");
        txtCardID.setText("");
        txtValid.setText("");
        txtY.setText("");
        txtM.setText("");
        txtD.setText("");
        txtAddress.setText("");
        imgMan.setImageDrawable(getResources().getDrawable(R.mipmap.ic_launcher));
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        readCardManager.readCardStop();
    }

}
      